package com.itlong.cloud.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.VO.app.AppElevatorAuthVO;
import com.itlong.cloud.POJO.VO.app.AppRoomAuthVO;
import com.itlong.cloud.app.dao.IAppRoomDao;
import com.itlong.cloud.app.service.IAppRoomService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      APP房间信息业务处理接口实现类
 * </desc>
 *
 * @createDate 2017/10/27
 */
@Service
public class AppRoomServiceImpl implements IAppRoomService{
    @Autowired
    IAppRoomDao iAppRoomDao;

    @Autowired
    MessageSender messageSender;
    /**
     * <desc>
     *      获取用户在项目中已认证的房屋
     * </desc>
     *
     * @param userId 用户id
     * @param projectId 项目id
     * @param owner 是否只查业主 1是 0否
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/27
     */
    @Override
    public List<AppRoomAuthVO> getUseRoomsByUserIdAndProjectId(String userId, String projectId,String owner) {
        List<Map<String,Object>> roomInfos=iAppRoomDao.getUseRoomsByUserIdAndProjectId(userId,projectId,owner);
        List<AppRoomAuthVO> rooms=new ArrayList<>();
        Set<String> roomIds = new HashSet<>();
        roomInfos.forEach(roomInfo->{
            AppRoomAuthVO roomVo=new AppRoomAuthVO();
            roomVo.setRoomName(StringHandlerUtil.getNullOrStringForObject(roomInfo.get("build_name"))+"-"
                                +StringHandlerUtil.getNullOrStringForObject(roomInfo.get("unit_name"))+"-"
                                +StringHandlerUtil.getNullOrStringForObject(roomInfo.get("room_num")));
            roomVo.setRoomNum(StringHandlerUtil.getNullOrStringForObject(roomInfo.get("room_id")));
            roomVo.setRoomId(roomInfo.get("room_id").toString());
            roomIds.add(roomVo.getRoomId());
            rooms.add(roomVo);
        });
        //获取房间剩余通行次数
        if(roomIds.size() > 0) {
            List<Map<String, Object>> lastCount = iAppRoomDao.getRoomLastCountByRoomId(roomIds);
            rooms.forEach(room -> {
                Optional<Map<String, Object>> optional = lastCount.stream().filter(map -> map.get("roomId").toString().equals(room.getRoomId())).findFirst();
                if (optional.isPresent()) {
                    room.setLastPassCount(optional.get().get("usableCount").toString());
                    room.setChargeMode(optional.get().get("chargeMode").toString());
                } else {
                    room.setChargeMode("1");
                    room.setLastPassCount("0");
                }
            });
        }else{
            rooms.forEach(room -> {
                room.setChargeMode("1");
                room.setLastPassCount("0");
            });
        }
        return rooms;
    }

    /**
     * <desc>
     *      添加访客时在非社区场景下获取业主的地址楼层列表
     * </desc>
     *
     * @param userId 用户id
     * @param projectId 项目id
     * @param owner 是否只查业主 1是 0否
     * @return
     * @author Juguang.S
     * @createDate 2021/03/26
     */
    @Override
    public List<AppRoomAuthVO> getOwnerUserFloorInfoByProjectId(String userId, String projectId,String owner) {
        //由于非社区场景 用户既有房间地址权限和分组权限 故需要分别查出并取并集
        List<Map<String,Object>> roomInfos=iAppRoomDao.getUseRoomsByUserIdAndProjectId(userId,projectId,owner);
        List<AppRoomAuthVO> rooms=new ArrayList<>();
        Set<String> roomIds = new HashSet<>();
        roomInfos.forEach(roomInfo->{
            AppRoomAuthVO roomVo=new AppRoomAuthVO();
            //此处查询单元地址下真实楼层在电梯楼层映射表中的楼层名称
            String logicalFloor = "";
            if(roomInfo.get("unitId")!=null && roomInfo.get("room_num") !=null){
                logicalFloor = iAppRoomDao.getUseRoomsFloorName(roomInfo.get("unitId")+"",Integer.parseInt((roomInfo.get("room_num")+"").substring(0,2))+"");
            }
            roomVo.setRoomName(StringHandlerUtil.getNullOrStringForObject(roomInfo.get("build_name"))+"-"
                    +StringHandlerUtil.getNullOrStringForObject(roomInfo.get("unit_name"))+"-"
                    +logicalFloor);
            roomVo.setRoomNum(StringHandlerUtil.getNullOrStringForObject(roomInfo.get("room_id")));
            roomVo.setRoomId(roomInfo.get("room_id").toString());
            roomIds.add(roomVo.getRoomId());
            rooms.add(roomVo);
        });

        //查询用户通过分组方式进行授权设备的地址楼层
        List<AppElevatorAuthDTO> auth = iAppRoomDao.getFloorAuth(userId, projectId);
        AppElevatorAuthVO elevator = StringHandlerUtil.convertElevatorAuth(auth);
        elevator.getElevatorAuth().forEach(authInfo -> {
            String deviceUnique = String.format("%s%s%s",projectId,1,authInfo.getDeviceId());
            String[] liveFloorArr = StringHandlerUtil.splitString(authInfo.getLiveFloor());
            //查询楼层名称及楼栋单元名称等信息
            List<Map<String,Object>> logcialFloorInfos=iAppRoomDao.getLogciaFloorAndAddressByDeivecUnique(deviceUnique,liveFloorArr);
            logcialFloorInfos.forEach(logcialFloor->{
                AppRoomAuthVO roomVo=new AppRoomAuthVO();
                roomVo.setRoomName(StringHandlerUtil.getNullOrStringForObject(logcialFloor.get("addressName")));
                roomVo.setRoomNum(StringHandlerUtil.getNullOrStringForObject(logcialFloor.get("logicalFloor")));
                roomVo.setRoomId(StringHandlerUtil.getNullOrStringForObject(logcialFloor.get("logicalFloor")));
                rooms.add(roomVo);
            });
        });

        return rooms;
    }

    /**
     * <desc>
     *      设置开门密码
     * </desc>
     *
     * @param projectId 项目id
     * @param userId 用户id
     * @param openPwd 开门密码
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer setOpenPwd(String projectId, String userId, String openPwd) throws Exception {
        //获取用户在当前项目下的所有房间
        String roomIds=iAppRoomDao.getUserProjectRoomIds(projectId,userId);
        //设置开门密码
        iAppRoomDao.setOpenPwd(StringHandlerUtil.splitString(roomIds),openPwd);
        //发送消息通知修改用户家属开门密码
        Map<String,Object> params=new HashMap<>();
        params.put("projectId",projectId);
        params.put("userId",userId);
        params.put("openPwd",openPwd);
        messageSender.send(RabbitMQConstant.RABBITMQ_UPDATE_FAMILY_OPENPWD_QUEUE, JSON.toJSONString(params),
                RabbitMQConstant.RABBITMQ_USER_EXCHANGE, RabbitMQConstant.RABBITMQ_UPDATE_FAMILY_OPENPWD_KEY);
        return 1;
    }

    /**
     * <desc>
     *      获取当前房屋列表，app2.0版本新增
     * </desc>
     *
     * @param projectId 项目编号
     * @param userId    用户id
     * @return 房屋列表
     * @author wangzhi
     * @createDate 2019/06/27
     */
    @Override
    public Map<String, Object> getHomeList(String projectId, String userId) throws Exception {
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> roomList = iAppRoomDao.getHomeList(projectId, userId);
        data.put("roomList", roomList == null ? new ArrayList<>() : roomList);
        return data;
    }
}
